// internal/api/router.go
package api

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"

	"virt-manager-go/internal/api/handlers"
	"virt-manager-go/internal/api/middleware"
	"virt-manager-go/internal/console"
	"virt-manager-go/internal/domain"
)

type Router struct {
	engine           *gin.Engine
	vmHandler        *handlers.VMHandler
	storageHandler   *handlers.StorageHandler
	networkHandler   *handlers.NetworkHandler
	snapshotHandler  *handlers.SnapshotHandler
	migrationHandler *handlers.MigrationHandler
	batchHandler     *handlers.BatchHandler
	eventHandler     *handlers.EventHandler
	connHandler      *handlers.ConnectionHandler
	serialHandler    *handlers.ConsoleHandler
	graphicsHandler  *handlers.GraphicsHandler
	logger           *logrus.Logger
}

func NewRouter(
	vmService domain.VMService,
	storageService domain.StoragePoolService,
	networkService domain.NetworkService,
	snapshotService domain.SnapshotService,
	migrationService domain.MigrationService,
	batchService domain.BatchService,
	eventService domain.EventService,
	serialProxy *console.SerialProxy,
	graphicsProxy *console.GraphicsProxy,
	connMgr domain.ConnectionManager,
	logger *logrus.Logger,
) *Router {
	// 设置 Gin 模式
	gin.SetMode(gin.ReleaseMode)

	engine := gin.New()

	// 全局中间件
	engine.Use(gin.Recovery())
	engine.Use(middleware.Logger(logger))
	engine.Use(middleware.CORS())

	// 创建处理器
	vmHandler := handlers.NewVMHandler(vmService, logger)
	connHandler := handlers.NewConnectionHandler(connMgr, logger)
	storageHandler := handlers.NewStorageHandler(storageService, logger)
	networkHandler := handlers.NewNetworkHandler(networkService, logger)
	snapshotHandler := handlers.NewSnapshotHandler(snapshotService, logger)
	migrationHandler := handlers.NewMigrationHandler(migrationService, logger)
	batchHandler := handlers.NewBatchHandler(batchService, logger)
	eventHandler := handlers.NewEventHandler(eventService, logger)
	serialHandler := handlers.NewConsoleHandler(serialProxy, logger)
	graphicsHandler := handlers.NewGraphicsHandler(graphicsProxy, logger)

	router := &Router{
		engine:           engine,
		vmHandler:        vmHandler,
		connHandler:      connHandler,
		storageHandler:   storageHandler,
		networkHandler:   networkHandler,
		snapshotHandler:  snapshotHandler,
		migrationHandler: migrationHandler,
		batchHandler:     batchHandler,
		eventHandler:     eventHandler,
		serialHandler:    serialHandler,
		graphicsHandler:  graphicsHandler,
		logger:           logger,
	}

	router.SetupExtendedRoutes()

	return router
}

// Engine 返回底层的 gin.Engine 实例
func (r *Router) Engine() *gin.Engine {
	return r.engine
}

func (r *Router) SetupExtendedRoutes() {
	// 健康检查
	r.engine.GET("/health", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"status":  "ok",
			"service": "virt-manager-go",
		})
	})

	v1 := r.engine.Group("/api/v1")
	{
		// ===== 连接管理 =====
		connections := v1.Group("/connections")
		{
			connections.POST("", r.connHandler.Connect)
			connections.GET("", r.connHandler.ListConnections)
			connections.DELETE("/:connection_id", r.connHandler.Disconnect)
			connections.GET("/:connection_id/capabilities", r.connHandler.GetCapabilities)

			// ===== 虚拟机管理 =====
			vms := connections.Group("/:connection_id/vms")
			{
				vms.GET("", r.vmHandler.ListVMs)
				vms.POST("", r.vmHandler.CreateVM)
				vms.GET("/:vm_name", r.vmHandler.GetVM)
				vms.DELETE("/:vm_name", r.vmHandler.DeleteVM)
				vms.PATCH("/:vm_name", r.vmHandler.UpdateVM)

				// 虚拟机操作
				vms.POST("/:vm_name/start", r.vmHandler.StartVM)
				vms.POST("/:vm_name/shutdown", r.vmHandler.ShutdownVM)
				vms.POST("/:vm_name/reboot", r.vmHandler.RebootVM)
				vms.POST("/:vm_name/suspend", r.vmHandler.SuspendVM)
				vms.POST("/:vm_name/resume", r.vmHandler.ResumeVM)
				vms.POST("/:vm_name/clone", r.vmHandler.CloneVM)

				// 配置管理
				vms.GET("/:vm_name/xml", r.vmHandler.GetVMXML)

				// 性能监控
				vms.GET("/:vm_name/metrics", r.vmHandler.GetVMMetrics)
				vms.GET("/:vm_name/metrics/stream", r.vmHandler.StreamVMMetrics)

				// ===== 快照管理 =====
				snapshots := vms.Group("/:vm_name/snapshots")
				{
					snapshots.GET("", r.snapshotHandler.ListSnapshots)
					snapshots.POST("", r.snapshotHandler.CreateSnapshot)
					snapshots.GET("/:snapshot_name", r.snapshotHandler.GetSnapshot)
					snapshots.DELETE("/:snapshot_name", r.snapshotHandler.DeleteSnapshot)
					snapshots.POST("/:snapshot_name/revert", r.snapshotHandler.RevertToSnapshot)
				}

				// ===== 迁移 =====
				vms.POST("/:vm_name/migrate", r.migrationHandler.MigrateVM)
			}

			// ===== 存储池管理 =====
			storage := connections.Group("/:connection_id/storage")
			{
				// 存储池
				storage.GET("/pools", r.storageHandler.ListPools)
				storage.POST("/pools", r.storageHandler.CreatePool)
				storage.GET("/pools/:pool_name", r.storageHandler.GetPool)
				storage.DELETE("/pools/:pool_name", r.storageHandler.DeletePool)
				storage.POST("/pools/:pool_name/start", r.storageHandler.StartPool)
				storage.POST("/pools/:pool_name/stop", r.storageHandler.StopPool)
				storage.POST("/pools/:pool_name/refresh", r.storageHandler.RefreshPool)

				// 存储卷
				storage.GET("/pools/:pool_name/volumes", r.storageHandler.ListVolumes)
				storage.POST("/pools/:pool_name/volumes", r.storageHandler.CreateVolume)
				storage.GET("/pools/:pool_name/volumes/:volume_name", r.storageHandler.GetVolume)
				storage.DELETE("/pools/:pool_name/volumes/:volume_name", r.storageHandler.DeleteVolume)
				storage.POST("/pools/:pool_name/volumes/:volume_name/clone", r.storageHandler.CloneVolume)
				storage.POST("/pools/:pool_name/volumes/:volume_name/resize", r.storageHandler.ResizeVolume)
			}

			// ===== 虚拟网络管理 =====
			networks := connections.Group("/:connection_id/networks")
			{
				networks.GET("", r.networkHandler.ListNetworks)
				networks.POST("", r.networkHandler.CreateNetwork)
				networks.GET("/:network_name", r.networkHandler.GetNetwork)
				networks.DELETE("/:network_name", r.networkHandler.DeleteNetwork)
				networks.POST("/:network_name/start", r.networkHandler.StartNetwork)
				networks.POST("/:network_name/stop", r.networkHandler.StopNetwork)
				networks.GET("/:network_name/dhcp-leases", r.networkHandler.GetDHCPLeases)
			}

			// ===== 批量操作 =====
			batch := connections.Group("/:connection_id/batch")
			{
				batch.POST("/vms/start", r.batchHandler.BatchStartVMs)
				batch.POST("/vms/stop", r.batchHandler.BatchStopVMs)
				batch.POST("/vms/reboot", r.batchHandler.BatchRebootVMs)
				batch.POST("/vms/delete", r.batchHandler.BatchDeleteVMs)
				batch.POST("/snapshots/create", r.batchHandler.BatchCreateSnapshots)
				// batch.POST("/snapshots/delete", r.batchHandler.BatchDeleteSnapshots)
				// batch.POST("/vms/update", r.batchHandler.BatchUpdateVMs)
				batch.GET("/status/:batch_id", r.batchHandler.GetBatchStatus)
			}
		}

		// ===== 迁移管理 =====
		migrations := v1.Group("/migrations")
		{
			migrations.GET("/:job_id", r.migrationHandler.GetMigrationStatus)
			migrations.POST("/:job_id/cancel", r.migrationHandler.CancelMigration)
		}

		console := v1.Group("/console")
		{
			// ===== 串行控制台 =====
			serial := console.Group("/serial")
			{
				// 获取连接信息
				serial.GET("/:connection_id/:vm_name/info", r.serialHandler.GetSerialInfo)

				// WebSocket 连接
				serial.GET("/:connection_id/:vm_name", r.serialHandler.HandleSerialWebSocket)

				// 会话管理
				serial.GET("/sessions", r.serialHandler.ListSerialSessions)
				serial.GET("/sessions/:session_id", r.serialHandler.GetSerialSession)
				serial.DELETE("/sessions/:session_id", r.serialHandler.CloseSerialSession)
				serial.DELETE("/:connection_id/:vm_name/sessions", r.serialHandler.CloseVMSerialSessions)

				// 统计信息
				serial.GET("/stats", r.serialHandler.GetSerialProxyStats)

				// 令牌管理
				serial.DELETE("/tokens/:token", r.serialHandler.RevokeSerialToken)
			}

			// ===== VNC 控制台 =====
			vnc := console.Group("/vnc")
			{
				vnc.GET("/:connection_id/:vm_name/info", r.graphicsHandler.GetVNCInfo)
				vnc.GET("/:connection_id/:vm_name", r.graphicsHandler.HandleVNCWebSocket)
			}

			// ===== SPICE 控制台 =====
			spice := console.Group("/spice")
			{
				spice.GET("/:connection_id/:vm_name/info", r.graphicsHandler.GetSPICEInfo)
				spice.GET("/:connection_id/:vm_name", r.graphicsHandler.HandleSPICEWebSocket)
			}

			// // ===== 图形控制台会话 =====
			// console.GET("/graphics/sessions", r.graphicsHandler.ListGraphicsSessions)

			// // ===== 通用控制台 API =====
			// console.GET("/:connection_id/:vm_name/types", r.graphicsHandler.GetConsoleTypes)
		}

		// ===== 事件系统 =====
		events := v1.Group("/events")
		{
			events.POST("/subscribe", r.eventHandler.SubscribeEvents) // SSE
			events.GET("/history", r.eventHandler.GetEvents)
			events.POST("/connections/:connection_id/listen", r.eventHandler.StartEventListener)
			events.POST("/connections/:connection_id/unlisten", r.eventHandler.StopEventListener)
		}
	}
}

func (r *Router) Run(addr string) error {
	r.logger.WithField("address", addr).Info("Starting HTTP server")
	return r.engine.Run(addr)
}
